from ..operation.base import verification_data
from ..model.user import UserSql, generate_password_hash


async def login_user(data):
    data = await verification_data(data)
    return {'message': 'The account or password is incorrect'} \
        if not data else UserSql().make_token(data['username'], data['password'])


async def list_user(data):
    user, page, size, page_count, count \
        = UserSql().page(username__like=data.get('username', ''), page=data.get('page', '')).value('id', 'username')
    return {'data': user, 'page': page, 'size': size, 'page_count': page_count, 'count': count}


async def add_user(data):
    data = await verification_data(data)
    if not data:
        return {'message': 'The parameter cannot be empty'}
    if UserSql().list(username=data['username']).value('password'):
        return {'message': 'The user already exists'}
    UserSql().creat(username=data['username'], password=generate_password_hash(data['password']))
    return {'message': 'Add a success'}


async def updata_user(data):
    uid = data.get('uid', None)
    if not uid:
        return {'message': 'The parameter cannot be empty'}
    UserSql().update(avatar=data.get('avatar', ''), phone=data.get('phone', ''), nickname=data.get('nickname', '')) \
        .where(uid)
    return {'message': 'Modify the success'}
